﻿import os
import random
import time
import sys

import pygame
import pygame.freetype

import locals
from utils.PygameUI import *
from utils.functions import *
from utils.rectangle import Rectangle
from utils.vector import Vector

from classes import *


class CachePic:
    def __init__(self, surface, name, rotate, screenMutt, opacity=None):
        self.surface = surface
        self.name = name
        self.rotate = rotate
        self.screenMutt = screenMutt
        self.opacity = opacity

    def isSamePicture(self, arrayArgs):
        # 数组的数据传导依次为name x y rotate screenMutt camera_x camera_y opacity
        if len(arrayArgs) == 7:
            if arrayArgs[0] == self.name and arrayArgs[3] == self.rotate and arrayArgs[4] == self.screenMutt:
                return True
            else:
                return False
        else:
            if arrayArgs[0] == self.name and arrayArgs[3] == self.rotate and arrayArgs[4] == self.screenMutt \
                and arrayArgs[7] == self.opacity:
                return True
            else:
                return False
    
    def draw_myself(self, arrayArgs):
        global screen, screenSize
        PictureLeft, PictureRight, PictureLength, PictureWidth = self.surface.get_rect()
        screen.blit(self.surface,
                    (int((arrayArgs[1] - arrayArgs[5]) * arrayArgs[4])
                     + screenSize[0] // 2 -
                     int(PictureLength // 2),
                     int((arrayArgs[2] - arrayArgs[6]) * arrayArgs[4])
                     + screenSize[1] // 2 -
                     int(PictureWidth // 2)))


def screen_prepared():
    global screen
    # 创建一个屏幕，并返回它的属性
    os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 30)
    displayInfo = pygame.display.Info()
    mutt_x, mutt_y = displayInfo.current_w / locals.SIZE_x * locals.Scared, \
    displayInfo.current_h / locals.SIZE_y * locals.Scared
    print("==========ScreenInfo===========")
    print("FirstDecided: ", mutt_x, mutt_y)
    if mutt_x > mutt_y:
        screen = pygame.display.set_mode((int(locals.SIZE_x * mutt_y), int(locals.SIZE_y * mutt_y)))
        muttSize = mutt_y
    else:
        screen = pygame.display.set_mode((int(locals.SIZE_x * mutt_x), int(locals.SIZE_y * mutt_x)))
        muttSize = mutt_x
    print("LastDecide: ", muttSize)
    print("SurfaceArgus: ", [int(locals.SIZE_x * mutt_y), int(locals.SIZE_y * mutt_y), muttSize])
    print("===============================")
    return screen, [int(locals.SIZE_x * mutt_y), int(locals.SIZE_y * mutt_y), muttSize]

def key_event():
    # 读取按键操作
    key = pygame.key.get_pressed()
    mouse = pygame.mouse.get_pos() + pygame.mouse.get_pressed()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            pass
    if key[pygame.K_ESCAPE]:
        sys.exit()
    return key, mouse

def get_file(bin_name):
    # 读取一个文件，并且储存以数组
    result_name = []
    result_surface = []
    for root, dirs, files in os.walk(bin_name):
        for file in files:
            name_array = os.path.join(root, file).split(r"\ "[0])
            name = name_array[-1].split(".")
            result_name.append(name[0])  # 每个文件对应名字
            result_surface.append(os.path.join(root, file))
    return result_name, result_surface

def readPictureFile(location):
    # 读取图片文件到自身的储存中
    global get_file, screenSize, pictureFile, pictureName
    pictureName, NotDealFile = get_file(location)
    for FileName in NotDealFile:
        Picture_nScaled = pygame.image.load(FileName).convert_alpha()
        PictureLeft, PictureRight, PictureLength, PictureWidth = Picture_nScaled.get_rect()
        Picture_Scaled = pygame.transform.scale(Picture_nScaled, (int(PictureLength * screenSize[2]),
                                                                  int(PictureWidth * screenSize[2])))
        pictureFile.append([Picture_Scaled, int(PictureLength * screenSize[2]),
                                 int(PictureWidth * screenSize[2])])
    print("==========PictureInfo==========")
    print(pictureName)
    print(pictureFile)
    print("===============================")

def changeUnitArgs(arrayArgs):
    # 更改entity中的内容
    # 数组的数据传导依次为 unit_id var_name new_arg
    global ListUI
    for each_entity in ListUI:
        if each_entity.id == arrayArgs[0]:
            if hasattr(each_entity, arrayArgs[1]):
                final_entity = each_entity
                setattr(final_entity, arrayArgs[1], arrayArgs[2])
                ListUI[ListUI.index(each_entity)] = final_entity

def showTheClasses(arrayArgs):
    global screenSize, ListUI
    ListUI = []
    ListUI.append(Picture("background", 0, 0))
    ListUI.append(LessonsExcel("classes", -screenSize[0] * 0.40, -screenSize[1] * 0.40, "lessons"))
    ListUI.append(Button("ExitButtonShowingLessons", screenSize[0] * 0.30, screenSize[1] * 0.40))

def showTheMainMenu(arrayArgs):
    global screenSize, ListUI
    ListUI = []
    ListUI.append(Picture("background", 0, 0))
    ListUI.append(Button("ButtonShowingLessons", -screenSize[0] * 0.30, screenSize[1] * 0.40))
    ListUI.append(Clock("clock", 0, 0))
    ListUI[2].color = (0, 0, 0)
    ListUI.append(ListLabel("timeList", screenSize[0] * 0.32, screenSize[1] * 0.40))
    ListUI.append(ListLabel("timeList", screenSize[0] * 0.26, screenSize[1] * 0.40))
    ListUI.append(ListLabel("timeList", screenSize[0] * 0.20, screenSize[1] * 0.40))
    ListUI.append(Text("sec", screenSize[0] * 0.85, screenSize[1] * 0.90))
    ListUI[6].color = (0, 0, 0)
    ListUI.append(ListLabel("showSubjects", screenSize[0] * 0.05, screenSize[1] * 0.40))
    ListUI.append(Button("ButtonAddScore", -screenSize[0] * 0.30, screenSize[1] * 0.28))
    ListUI.append(Button("ButtonShowingScore", -screenSize[0] * 0.30, screenSize[1] * 0.16))
    ListUI.append(Text("v1.01-Beta", 0, 20 * screenSize[2]))
    ListUI[10].color = (0, 0, 0)
    ListUI.append(Button("ButtonShowRank", -screenSize[0] * 0.30, screenSize[1] * 0.04))

def AddScore(arrayArgs):
    global ListUI, subject_name, subject_translate, showTheScore
    now_score = int(ListUI[3].listAbout[ListUI[3].select_on]) + int(ListUI[4].listAbout[ListUI[4].select_on]) * 10 + \
        int(ListUI[5].listAbout[ListUI[5].select_on]) * 100
    add_score(subject_name[subject_translate.index(ListUI[7].listAbout[ListUI[7].select_on])], now_score)
    showTheScore([])

def showTheScore(arrayArgs):
    global screenSize, ListUI, subject_name, subject_translate
    path_name = subject_name[subject_translate.index(ListUI[7].listAbout[ListUI[7].select_on])]
    ListUI = []
    ListUI.append(Picture("background", 0, 0))
    ListUI.append(Button("ExitButtonShowingScore", screenSize[0] * 0.30, screenSize[1] * 0.40))
    scores, avg = take_score(path_name)
    ListUI.append(Picture("scorehead", -screenSize[0] * 0.20, -screenSize[1] * 0.40))
    ListUI.append(TextLabel("scoreExcel", -screenSize[0] * 0.20, -screenSize[1] * 0.40 + int(225 * screenSize[2])))
    ListUI[3].speak = scores

def showTheRank(arrayArgs):
    global screenSize, ListUI
    ListUI = []
    ListUI.append(Picture("background", 0, 0))
    ListUI.append(Button("ExitButtonShowingScore", screenSize[0] * 0.30, screenSize[1] * 0.40))
    ranking = take_avg_rank()
    ListUI.append(Picture("rankhead", -screenSize[0] * 0.25, -screenSize[1] * 0.40))
    ListUI.append(TextLabel("scoreExcel", -screenSize[0] * 0.25, -screenSize[1] * 0.40 + int(225 * screenSize[2])))
    ListUI[3].speak = ranking
    ranking = take_squ_rank()
    ListUI.append(Picture("rankhead_2", screenSize[0] * 0.25, -screenSize[1] * 0.40))
    ListUI.append(TextLabel("scoreExcel", screenSize[0] * 0.25, -screenSize[1] * 0.40 + int(225 * screenSize[2])))
    ListUI[5].speak = ranking

def deBugEvent(arrayArgs):
    print("This Event Has Been Used.")

def drawText(arrayArgs):
    # 将文字输出到屏幕上（绝对坐标）
    # 数组的数据传导依次为text pos color
    global fontObj
    text1 = fontObj.render(arrayArgs[0], False, arrayArgs[2])
    screen.blit(text1, arrayArgs[1])

def drawRec(arrayArgs):
    # 在屏幕上输出一个矩形
    # 数组的数据传导依次为color pos width
    global screen
    pos_x, pos_y, dx, dy = arrayArgs[1]
    if dx < 0:
        pos_x = pos_x + dx
        dx = -dx
    if dy < 0:
        pos_y = pos_y + dy
        dy = -dy
    pygame.draw.rect(screen, arrayArgs[0], (pos_x, pos_y, dx, dy), arrayArgs[2])

def drawPicture(arrayArgs):
    # 将图片输出在屏幕上（绝对坐标）
    # 数组的数据传导依次为name x y rotate screenMutt camera_x camera_y opacity
    global screen, screenSize, pictureFile, pictureName, pictureCache
    if pictureCache != []:
        for each_cache in pictureCache:
            if each_cache.isSamePicture(arrayArgs):
                each_cache.draw_myself(arrayArgs)
                return
    Picture_Mutt2 = pygame.transform.scale(pictureFile[pictureName.index(arrayArgs[0])][0],
                                           (int(pictureFile[pictureName.index(arrayArgs[0])][1]
                                                * arrayArgs[4]),
                                            int(pictureFile[pictureName.index(arrayArgs[0])][2]
                                                * arrayArgs[4])))
    if arrayArgs[3] is not None:
        Picture_Mutt2 = pygame.transform.rotate(Picture_Mutt2, -arrayArgs[3])
    PictureLeft, PictureRight, PictureLength, PictureWidth = Picture_Mutt2.get_rect()
    if len(arrayArgs) > 7:
        Picture_Mutt3 = pygame.Surface((Picture_Mutt2.get_width(), Picture_Mutt2.get_height())).convert()
        Picture_Mutt3.blit(screen, (-int((arrayArgs[1] - arrayArgs[5]) * arrayArgs[4])
                                    + screenSize[0] // 2 -
                                    int(PictureLength // 2), -int((arrayArgs[2] - arrayArgs[6]) * arrayArgs[4])
                 + screenSize[1] // 2 -
                 int(PictureWidth // 2) ))
        Picture_Mutt3.blit(Picture_Mutt2, (0, 0))
        Picture_Mutt3.set_alpha(arrayArgs[7])
        screen.blit(Picture_Mutt3,
                    (int((arrayArgs[1] - arrayArgs[5]) * arrayArgs[4])
                     + screenSize[0] // 2 -
                     int(PictureLength // 2),
                     int((arrayArgs[2] - arrayArgs[6]) * arrayArgs[4])
                     + screenSize[1] // 2 -
                     int(PictureWidth // 2)))
        preparedCache = CachePic(Picture_Mutt3, arrayArgs[0], arrayArgs[3], arrayArgs[4], arrayArgs[7])
        pictureCache.append(preparedCache)
        return
    screen.blit(Picture_Mutt2,
                (int((arrayArgs[1] - arrayArgs[5]) * arrayArgs[4])
                 + screenSize[0] // 2 -
                 int(PictureLength // 2),
                 int((arrayArgs[2] - arrayArgs[6]) * arrayArgs[4])
                 + screenSize[1] // 2 -
                 int(PictureWidth // 2)))
    preparedCache = CachePic(Picture_Mutt2, arrayArgs[0], arrayArgs[3], arrayArgs[4])
    pictureCache.append(preparedCache)

# 定义
pygame.init()
screen, screenSize = screen_prepared()
pygame.display.set_caption(locals.TITLE)
# 本机
fontObj = pygame.font.Font("bin/fonts/pixel14.ttf", int(18 * screenSize[2]))
ListUI = []
showTheMainMenu([])
# 图像文件的存储
pictureFile = []
pictureName = []
pictureCache = []
# 读取图片文件
readPictureFile("bin/images")
iconImg = pygame.image.load("icon.ico")
pygame.display.set_icon(iconImg)
# 帧率
clock = pygame.time.Clock()
# 对应的学科
subject_name = ["chi", "math", "eng", "phy", "chem", "bio", "his", "geo", "pol"]
subject_translate = ["语文", "数学", "英语", "物理", "化学", "生物", "历史", "地理", "政治"]

# 主程序
def main():
    global clock, ListUI, screenSize
    while True:
        clock.tick(60)
        NowFps = clock.get_fps()
        screen.fill(locals.BLACK)
        now_keys, now_mouse = key_event()
        for each_ui in ListUI:
            outputEventArray = []
            outputEventArray = each_ui.self_event((now_keys, now_mouse, ListUI, screenSize))
            if outputEventArray != [] and outputEventArray is not None:
                try:
                    for each_event in outputEventArray:
                        eval(each_event.event)(each_event.args)
                except:
                    raise ValueError("错误的事件被调用："+str(each_event.event)+" - "+
                                     each_event.args)
        # Fps
        eval("drawText")([str(int(NowFps)), (100, 100), (255, 0, 0)])
        pygame.display.update()

if __name__ == "__main__":
    main()
